package warmachineroster.presentation.policy;

import java.util.List;

import org.eclipse.gef.EditPart;
import org.eclipse.gef.EditPolicy;
import org.eclipse.gef.commands.Command;
import org.eclipse.gef.commands.CompoundCommand;
import org.eclipse.gef.commands.UnexecutableCommand;
import org.eclipse.gef.editpolicies.FlowLayoutEditPolicy;
import org.eclipse.gef.requests.CreateRequest;

import warmachineroster.RosterElement;
import warmachineroster.UnitRosterElement;
import warmachineroster.presentation.command.UnitAttachmentRosterElementCreateCommand;
import warmachineroster.presentation.command.UnitAttachmentRosterElementMoveCommand;
import warmachineroster.presentation.editpart.UnitRosterElementEditPart;
import warmachinesystem.UnitAttachment;

public class UnitFlowLayoutEditPolicy extends FlowLayoutEditPolicy
		implements EditPolicy {

	@Override
	protected Command createAddCommand(EditPart child, EditPart after) {
		return UnexecutableCommand.INSTANCE;
	}

	@Override
	protected Command createMoveChildCommand(EditPart child, EditPart after) {
		if (after != null){
			RosterElement childModel = (RosterElement) child.getModel();
			int oldIndex = getHost().getChildren().indexOf(child);
			int newIndex = getHost().getChildren().indexOf(after);
			UnitRosterElement warcasterRosterElement = (UnitRosterElement) getHost().getModel(); 
			UnitAttachmentRosterElementMoveCommand command = new UnitAttachmentRosterElementMoveCommand();
			command.setUnitRosterElement(warcasterRosterElement);
			command.setUnitAttachmentRosterElement(childModel);
			command.setOldIndex(oldIndex);
			command.setNewIndex(newIndex);
			return command;
		}
		return UnexecutableCommand.INSTANCE;
	}

	@Override
	protected Command getCreateCommand(CreateRequest request) {
		Object newObject = request.getNewObject();
		return getCreateCommand(newObject);
	} 

	protected Command getCreateCommand(Object newObject) {
		if (newObject instanceof RosterElement && ((RosterElement)newObject).getUnitType() instanceof UnitAttachment){
			UnitAttachmentRosterElementCreateCommand command = new UnitAttachmentRosterElementCreateCommand();
			command.setUnitAttachmentRosterElement((RosterElement)newObject);
			UnitRosterElementEditPart weEditPart = (UnitRosterElementEditPart) getHost();
			command.setUnitRosterElement(weEditPart.getUnitRosterElement());
			return command;
		} else if (newObject instanceof List){
			CompoundCommand ccommand = new CompoundCommand();
			for(Object elem: (List<?>)newObject){
				ccommand.add(getCreateCommand(elem));
			}
			return ccommand;
		}
		
		return UnexecutableCommand.INSTANCE;
	}

}
